<script setup lang="ts">
import { pointApi } from '@/api'
import type { Point } from '@/components/ReadonlyPointTree/ReadonlyPointTree'

const emit = defineEmits<{
  (e: 'loaded', val: number): void
}>()

const pointId = defineModel<number>()
const pointTreeData = ref<Point[]>([])

const userStore = useUserStore()

function getFirstPointId() {
  return pointTreeData.value[0]?.id
}

onMounted(async () => {
  if (userStore.pointTree.length > 0) {
    pointTreeData.value = userStore.pointTree
  }
  else {
    const { data } = await pointApi.loadRoleEnergyUnit()
    pointTreeData.value = data.list || []
    userStore.setPointTree(pointTreeData.value)
  }
  emit('loaded', getFirstPointId())
})

defineExpose({
  getFirstPointId,
})
</script>

<template>
  <ElCascader
    v-model="pointId"
    :options="(pointTreeData as any)"
    :props="{
      value: 'id',
      label: 'pointName',
      children: 'children',
      checkStrictly: true,
      emitPath: false,
    }"
    v-bind="$attrs"
    placeholder="请选择用能单元"
    style="width: 100%"
    clearable
  />
</template>
